"""
员工管理API端点
"""
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.employee import Employee
from app.schemas.employee import EmployeeCreate, EmployeeUpdate, EmployeeResponse
from app.api.deps import get_current_active_user

router = APIRouter()


@router.get("/", response_model=List[EmployeeResponse])
def get_employees(
    db: Session = Depends(get_db),
    skip: int = 0,
    limit: int = 100,
    department_id: int = None,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    获取员工列表
    """
    query = db.query(Employee)
    if department_id:
        query = query.filter(Employee.department_id == department_id)
    
    employees = query.offset(skip).limit(limit).all()
    return employees


@router.get("/{employee_id}", response_model=EmployeeResponse)
def get_employee(
    employee_id: int,
    db: Session = Depends(get_db),
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    获取单个员工信息
    """
    employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not employee:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="员工不存在"
        )
    return employee


@router.post("/", response_model=EmployeeResponse)
def create_employee(
    *,
    db: Session = Depends(get_db),
    employee_in: EmployeeCreate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    创建新员工
    """
    # 检查员工编号是否已存在
    existing_employee = db.query(Employee).filter(
        Employee.employee_no == employee_in.employee_no
    ).first()
    if existing_employee:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="员工编号已存在"
        )
    
    employee = Employee(**employee_in.dict())
    db.add(employee)
    db.commit()
    db.refresh(employee)
    return employee


@router.put("/{employee_id}", response_model=EmployeeResponse)
def update_employee(
    *,
    db: Session = Depends(get_db),
    employee_id: int,
    employee_in: EmployeeUpdate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    更新员工信息
    """
    employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not employee:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="员工不存在"
        )
    
    # 如果更新员工编号，检查是否重复
    if employee_in.employee_no and employee_in.employee_no != employee.employee_no:
        existing_employee = db.query(Employee).filter(
            Employee.employee_no == employee_in.employee_no
        ).first()
        if existing_employee:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="员工编号已存在"
            )
    
    update_data = employee_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(employee, field, value)
    
    db.add(employee)
    db.commit()
    db.refresh(employee)
    return employee


@router.delete("/{employee_id}")
def delete_employee(
    *,
    db: Session = Depends(get_db),
    employee_id: int,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    删除员工
    """
    employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not employee:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="员工不存在"
        )
    
    db.delete(employee)
    db.commit()
    return {"message": "员工删除成功"}
